package com.fishery.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.search.entity.Diagnose;
import com.fishery.search.mapper.DiagnoseMapper;
import com.fishery.search.service.DiagnoseSearch;
import com.fishery.search.service.DiagnoseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;


@Service
public class DiagnoseServiceImpl extends ServiceImpl<DiagnoseMapper, Diagnose> implements DiagnoseService {

	@Autowired
	private DiagnoseMapper diagonoseMapper;

	@Autowired
	private DiagnoseSearch diagnoseSearch;

	@Autowired
	private ExecutorService threadPool;

	@Autowired
	private RedisTemplate redisTemplate;


	@Override
	public boolean saveArticle(Diagnose diagnose) {
		int ret = diagonoseMapper.insert(diagnose);
		return ret > 0;
	}

	@Override
	public boolean deleteArticle(String id) {
		// 开启一条线程处理
		threadPool.submit(() -> diagnoseSearch.deleteDocumentById(id));
		int ret = diagonoseMapper.deleteById(id);
		return ret > 0;
	}

	@Override
	public Page<Diagnose> getDiseaseDiagnoseInfo(String userId, int current, int size) {
		Page<Diagnose> page = new Page<>(current < 0 ? 1 : current, size <= 0 ? 5 : size);
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id", userId);
		diagonoseMapper.selectPage(page, wrapper);
		return page;
	}

	@Override
	public boolean updateArticle(Diagnose diagnose) {
		return diagonoseMapper.updateByIdAndUserId(diagnose) > 0;
	}

	@Override
	public Diagnose getArticleById(String articleId, String uerId) {
		// 查询疾病文章
		Diagnose diagnose = diagonoseMapper.selectById(articleId);
		// 采用redis统计阅读量
		List userIdList = (List) redisTemplate.opsForHash().get("DIAGNOSE_READ_AMOUNT", articleId);
		if (userIdList == null || !userIdList.contains(uerId)) {
			if (userIdList == null) {
				userIdList = new ArrayList();
			}
			userIdList.add(uerId);
			redisTemplate.opsForHash().put("DIAGNOSE_READ_AMOUNT", articleId, userIdList);
		}
		return diagnose;
	}

	@Override
	public boolean updateReadAmountOfArticleToDB() {
		// 更新redis中的阅读量到数据库
		Set<String> articleIdSet = redisTemplate.opsForHash().keys("DIAGNOSE_READ_AMOUNT");
		articleIdSet.forEach(articleId -> {
			int readAmount = ((List) (redisTemplate.opsForHash()
					.get("DIAGNOSE_READ_AMOUNT", articleId))).size();
			diagonoseMapper.increaseReadAmountOfArticle(articleId, readAmount);
		});
		redisTemplate.delete("DIAGNOSE_READ_AMOUNT");
		return true;
	}
}
